package com.cxs.util;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @Author CXS
 * @Date 2024/1/26 14:21
 **/
public class MqttUtil {

    public static final String BROKER = "tcp://cxs-vm:1883";

    public static final String USER_NAME = "cxs";

    public static final String PASSWORD = "123456";


    public static MqttClient createMqttClient(String clientId, Boolean CleanSession) {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = null;
        try {
            client = new MqttClient(BROKER, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(USER_NAME);
            connOpts.setPassword(PASSWORD.toCharArray());
            // 保留会话
            connOpts.setCleanSession(CleanSession);
            client.connect(connOpts);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return client;
    }


}
